/*
 * @lc app=leetcode.cn id=654 lang=typescript
 *
 * [654] 最大二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：递归
//  首先创造出根节点，然后再递归数组的左右部分

//  复杂度：O(n2) O(n)

function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
    if (!nums.length) return null
    const max = Math.max(...nums), index = nums.indexOf(max)
    const root = new TreeNode(max)
    root.left = constructMaximumBinaryTree(nums.slice(0, index))
    root.right = constructMaximumBinaryTree(nums.slice(index + 1))

    return root
};
// @lc code=end

import { TreeNode } from './type'

const arr = [3, 2, 1, 6, 0, 5]
console.log(TreeNode.printTree(constructMaximumBinaryTree(arr)))
